package com.lys.emsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lys.emsystem.entity.LoginLog;
import com.lys.emsystem.entity.Role;
import com.lys.emsystem.mapper.LoginLogMapper;
import com.lys.emsystem.service.ILoginLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lys.emsystem.service.IRoleService;
import com.lys.emsystem.utils.Addr;
import com.lys.emsystem.utils.Result;
import com.lys.emsystem.vo.LoginLogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyansheng
 * @since 2022-05-06
 */
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private LoginLogMapper loginLogMapper;

    @Override
    public void registerLoginLog(String name, Integer roleId, HttpServletRequest request) {
    //    获取当前时间
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        //    获取角色名
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.eq("id", roleId);
        Role role = roleService.getOne(wrapper);

        LoginLog loginLog = new LoginLog();
        loginLog.setLoginTime(time);
        loginLog.setIp(Addr.getIpAddr(request));
        loginLog.setRole(role.getName());
        loginLog.setName(name);

    //    保存到数据库
        loginLogMapper.insert(loginLog);
    }

    @Override
    public Result search(Page page, LoginLogVo loginLogVo) {
        IPage<LoginLog> iPage = loginLogMapper.search(page, loginLogVo);
        if (iPage == null) {
            return Result.buildResult(Result.Status.ERROR, "查无数据");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("totalCount", iPage.getTotal());
        map.put("list", iPage.getRecords());
        return Result.buildResult(Result.Status.OK, map);
    }
}
